/*
 *
 *  * Copyright (c) 2016. For Intelligent Group.
 *
 */
package com.intelligent.ispc.client.core.controller;

import com.google.common.collect.Lists;

import com.intelligent.ispc.client.core.view.system.ScriptTestPanel;
import com.intelligent.ispc.client.event.ThrowExceptionEvent;
import com.intelligent.ispc.client.utils.ApplicationBeanUtils;
import com.intelligent.ispc.client.utils.EventBusUtils;
import com.intelligent.ispc.common.utils.ApplicationException;
import com.intelligent.ispc.common.utils.ExceptionMessages;
import com.intelligent.ispc.common.utils.ResourceBundleUtils;
import com.intelligent.ispc.utils.PythonUtil;

import com.itextpdf.text.log.Logger;
import com.itextpdf.text.log.LoggerFactory;

import org.springframework.stereotype.Component;

import java.io.File;
import java.util.List;

/**
 * Created by QiangChen on 2016/9/7.
 */
@Component
public class ScriptController {
    private final Logger logger = LoggerFactory.getLogger(ScriptController.class);

    public List<String> testScript(String filePath, String scriptPath, int rowNum, int columnNum) {
        logger.debug("Test Python script");

        List<String> result = Lists.newArrayList();
        List<String> filePaths = Lists.newArrayList();

        try {
            File file = new File(filePath);
            File script = new File(scriptPath);

            if (!file.isFile() || !script.isFile()) {
                throw new ApplicationException(ExceptionMessages.ERR_15004, ResourceBundleUtils.getString(ExceptionMessages.EXCEPTION_GLOBAL_FILE_PATH_DOESNOT_EXIST));
            }

            filePaths.add(filePath);

            result = new PythonUtil().getDataForScriptTest(filePaths, scriptPath, rowNum, columnNum);
        } catch (ApplicationException e) {
            if (e.getCode() == ExceptionMessages.ERR_15004) {
                ApplicationBeanUtils.getBean(ScriptTestPanel.class).filePathError(e.getFullMessage());
            } else if (e.getCode() == ExceptionMessages.ERR_15003) {
                ApplicationBeanUtils.getBean(ScriptTestPanel.class).scriptError(e.getFullMessage());
            } else {
                EventBusUtils.post(new ThrowExceptionEvent(e.getFullMessage()));
            }
        } catch (Exception e) {
            EventBusUtils.post(new ThrowExceptionEvent(ExceptionMessages.ERR_20001, e.getMessage()));
        }
        return result;
    }

}